package com.ruoyi.web.controller.system;

import cn.hutool.core.collection.CollUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.*;
import com.ruoyi.system.domain.Project;
import com.ruoyi.system.domain.AsyncDetail;
import com.ruoyi.system.domain.Product;
import com.ruoyi.system.domain.ValidationGroups.Create;
import com.ruoyi.system.domain.ValidationGroups.Select;
import com.ruoyi.system.domain.ValidationGroups.Update;
import com.ruoyi.system.domain.vo.QueryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;

import lombok.extern.slf4j.Slf4j;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.validation.constraints.NotNull;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.ServletUtils;

@SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
@Slf4j
@RestController
@RequestMapping("/system/project.v2")
public class ProjectController extends BaseController {
    @Autowired
    private IProjectService projectService;

    @Autowired
    private IDeviceService deviceService;

    @Autowired
    private IProductService productService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    private AsyncService asyncService;

    @Autowired
    private IAsyncDetailService asyncDetailService;

    @Autowired
    private IProjectAuthorizeService projectAuthorizeService;
    @Autowired
    private ICustomPermissionService customPermissionService;
    @Autowired
    private ISysUserService sysUserService;

    private AjaxResult checkExistance(Project project) {
        Map<String, Object> existance = projectService.findExistance(project);
        if (existance != null) {
            Object name_exists = existance.get("name_exists");
            if (name_exists != null && Integer.parseInt(name_exists.toString()) > 0) {
                return AjaxResult.error(HttpStatus.ERROR, "项目名称已经存在");
            }
            Object code_exists = existance.get("code_exists");
            if (code_exists != null && Integer.parseInt(code_exists.toString()) > 0) {
                return AjaxResult.error(HttpStatus.ERROR, "合同号已经存在");
            }
            Object peer_code_exists = existance.get("peer_code_exists");
            if (peer_code_exists != null && Integer.parseInt(peer_code_exists.toString()) > 0) {
                return AjaxResult.error(HttpStatus.ERROR, "客户合同号已经存在");
            }
        }
        return null;
    }

    @PreAuthorize("@ss.hasPermi('system:project:add')")
    @PostMapping(value = "/add", produces = "application/json;charset=UTF-8")
    @Log(title = "项目", businessType = BusinessType.INSERT)
    public AjaxResult add(@RequestBody @Validated(Create.class) Project project) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
        String createBy = loginUser.getUsername();
        project.setCompanyId(companyId);
        project.setCreateBy(createBy);
        project.setCreateTime(new Date());
        AjaxResult ret = checkExistance(project);
        if (ret != null) {
            return ret;
        }
        Integer id = projectService.create(project);
        if (id != null) {
            return AjaxResult.success(project);
        }
        return AjaxResult.error(MessageUtils.message("error.operation_failed"));
    }

    @PreAuthorize("@ss.hasPermi('system:project:add')")
    @PostMapping(value = "/import", produces = "application/json;charset=UTF-8")
    @Log(title = "项目", businessType = BusinessType.INSERT)
    public AjaxResult inject(@RequestBody JSONObject request) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
        String filename = request.getString("filename");
        String tid = asyncDetailService.createTid("导入项目", companyId);
        asyncService.injectProjects(tid, filename, loginUser.getUsername(), companyId);
        return AjaxResult.success(tid);
    }

    @PreAuthorize("@ss.hasPermi('system:project:add')")
    @PostMapping(value = "/import_result", produces = "application/json;charset=UTF-8")
    public AjaxResult injectResult(@RequestBody JSONObject request) {
        String tid = request.getString("tid");
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("tid", tid);
        AsyncDetail asyncDetail = asyncDetailService.retrieve(queryVo);
        JSONObject result = new JSONObject();
        Integer status = asyncDetail.getStatus();
        result.put("status", status);
        if (status > 0) {
            String output = asyncDetail.getData();
            try {
                result.put("output", JSON.parse(output));
            } catch (Exception e) {
                result.put("output", output);
            }
        }
        return AjaxResult.success(result);
    }

    @PreAuthorize("@ss.hasPermi('system:project:list')")
    @GetMapping(value = "/list", produces = "application/json;charset=UTF-8")
    public Object index(@Validated(Select.class) Project project) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("code", project.getCode());
        queryVo.filters.put("peer_code", project.getPeerCode());
        queryVo.filters.put("name", project.getName());
        queryVo.filters.put("area_code", project.getAreaCode());
        queryVo.filters.put("dept_id", project.getDeptId());
        queryVo.filters.put("address", project.getAddress());
        queryVo.filters.put("is_on", project.getIsOn());
        queryVo.filters.put("type", project.getType());
        queryVo.filters.put("remark", project.getRemark());
        queryVo.filters.put("input_time_start", project.getInputTimeStart());
        queryVo.filters.put("input_time_end", project.getInputTimeEnd());
        queryVo.filters.put("company_id", companyId);
        boolean commonRoleFlag = sysUserService.checkUserIsCommonRole(loginUser.getUser());
        if (!commonRoleFlag){
            String permission = customPermissionService.getProjectAuthorizePermission("p", null, loginUser.getUser());
            queryVo.setCustomPermissionSql(permission);
        }
        boolean flag = sysDeptService.checkIsCustomer(loginUser.getUser().getDeptId());
        startPage();
        List<Project> projects = projectService.index(queryVo);
        //客户公司下面过滤项目合同号
        if (flag && CollUtil.isNotEmpty(projects)){
            projects.forEach(a ->{
                a.setCode(null);
            });
        }
        return getDataTable(projects);
    }

    @PreAuthorize("@ss.hasPermi('system:project:query')")
    @GetMapping(value = "/{id}", produces = "application/json;charset=UTF-8")
    public AjaxResult retrieve(@PathVariable("id") @NotNull(message = "id不能为null") Integer id) {
        //TODO 验证当前用户是否在该项目的授权列表中
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        //验证设计员权限
        boolean commonRoleFlag = sysUserService.checkUserIsCommonRole(loginUser.getUser());
        if (!commonRoleFlag){
            projectAuthorizeService.checkProjectIsAuthorizeWithProjectId(loginUser.getUser(),id);
        }
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("id", id);
        Project project = projectService.retrieve(queryVo);
        if (project == null) {
            return AjaxResult.error(HttpStatus.NOT_FOUND, MessageUtils.message("error.not_found"));
        }
        return AjaxResult.success(project);
    }

    @PreAuthorize("@ss.hasPermi('system:project:edit')")
    @Log(title = "项目", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/edit", produces = "application/json;charset=UTF-8")
    public AjaxResult edit(@RequestBody @Validated(Update.class) Project project) {
        //TODO 验证当前用户是否在该项目的授权列表中
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        projectAuthorizeService.checkProjectIsAuthorizeWithProjectId(loginUser.getUser(),project.getId());
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("id", project.getId());
        Project target = projectService.retrieve(queryVo);
        if (target == null) {
            return AjaxResult.error(HttpStatus.NOT_FOUND, MessageUtils.message("error.not_found"));
        }
        project.setCompanyId(target.getCompanyId());
        AjaxResult ret = checkExistance(project);
        if (ret != null) {
            return ret;
        }
        if (projectService.update(project)) {
            return AjaxResult.success();
        }
        return AjaxResult.error(MessageUtils.message("error.operation_failed"));
    }

    @PreAuthorize("@ss.hasPermi('system:project:device:add')")
    @Log(title = "产品", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/{id}/device/add", produces = "application/json;charset=UTF-8")
    public AjaxResult addDevice(@PathVariable("id") @NotNull(message = "id不能为null") Integer id, @RequestBody JSONArray deviceIds) {
        //TODO 验证当前用户是否在该项目的授权列表中
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        projectAuthorizeService.checkProjectIsAuthorizeWithProjectId(loginUser.getUser(),id);
        Iterator<Object> iterator = deviceIds.iterator();
        List<Integer> deviceIdList = new ArrayList<>();
        while (iterator.hasNext()) {
            deviceIdList.add(Integer.parseInt(iterator.next().toString()));
        }
        deviceIdList.forEach(a ->{
            projectAuthorizeService.checkDeviceOperationStatus(loginUser.getUser(),a);
        });
        Integer affected = deviceService.addToProject(deviceIdList, id);
        return AjaxResult.success(affected);
    }

    @PreAuthorize("@ss.hasPermi('system:project:device:remove')")
    @Log(title = "产品", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/{id}/device/remove", produces = "application/json;charset=UTF-8")
    public AjaxResult removeDevice(@PathVariable("id") @NotNull(message = "id不能为null") Integer id, @RequestBody JSONArray deviceIds) {
        //TODO 验证当前用户是否在该项目的授权列表中
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        projectAuthorizeService.checkProjectIsAuthorizeWithProjectId(loginUser.getUser(),id);
        Iterator<Object> iterator = deviceIds.iterator();
        List<Integer> deviceIdList = new ArrayList<>();
        while (iterator.hasNext()) {
            deviceIdList.add(Integer.parseInt(iterator.next().toString()));
        }
        deviceIdList.forEach(a ->{
            projectAuthorizeService.checkDeviceOperationStatus(loginUser.getUser(),a);
        });
        Integer affected = deviceService.removeFromProject(deviceIdList);
        return AjaxResult.success(affected);
    }

    @PreAuthorize("@ss.hasPermi('system:project:product:list')")
    @GetMapping(value = "/{project_id}/product/list", produces = "application/json;charset=UTF-8")
    public TableDataInfo productIndex(@PathVariable("project_id") @NotNull(message = "id不能为null") Integer projectId, @ModelAttribute @Validated(Select.class) Product product) {
        //TODO 验证当前用户是否在该项目的授权列表中
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        boolean commonRoleFlag = sysUserService.checkUserIsCommonRole(loginUser.getUser());
        if (!commonRoleFlag){
            projectAuthorizeService.checkProjectIsAuthorizeWithProjectId(loginUser.getUser(),projectId);
        }
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("project_id", projectId);
        queryVo.filters.put("name", product.getName());
        queryVo.filters.put("code", product.getCode());
        queryVo.filters.put("manufacturer", product.getManufacturer());
        queryVo.filters.put("description", product.getDescription());
        startPage();
        return getDataTable(productService.projectIndex(queryVo));
    }
}
